package app.repositories.impl;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.StringUtils;

import app.models.Debito;
import app.repositories.DebitoRepository;
import app.repositories.Repository;
import br.com.caelum.vraptor.ioc.Component;

@Component
public class DebitoRepositoryImpl extends Repository<Debito, Long> implements DebitoRepository {

	private final String DATA_CADASTRO = "dataCadastro";
	private final String HORA_CADASTRO = "horaCadastro";
	private final String DESCRICAO = "descricao";
	
	
	protected DebitoRepositoryImpl(EntityManager entityManager) {
		super(entityManager);
	}
	
	@Override
	public List<Debito> findByPeriod(String dataInicial, String dataFinal) {
		Criteria criteria = createCriteria();
		
		criteria.add(Restrictions.between(DATA_CADASTRO, dataInicial, dataFinal));
		
		return criteria.list();
	}
	
	@Override
	public List<Debito> findByFilter(String filter) {
		Criteria criteria = createCriteria();
		
		if (StringUtils.hasLength(filter)) {
			criteria.add(Restrictions.ilike(DESCRICAO, filter, MatchMode.ANYWHERE));
			criteria.addOrder(Order.asc(DESCRICAO));
		}
		
		return criteria.list();
	}
	
	@Override
	public List<Debito> findAllOrdered() {
		Criteria criteria = createCriteria();
		
		criteria.addOrder(Order.asc(DESCRICAO));
		criteria.setMaxResults(10);
		
		return criteria.list();
	}
	
	@Override
	public List<Debito> findLastDebitos() {
		Criteria criteria = createCriteria();
		
		criteria.addOrder(Order.desc(DATA_CADASTRO));
		criteria.addOrder(Order.desc(HORA_CADASTRO));
		criteria.setMaxResults(10);
		
		return criteria.list();
	}

}
